﻿namespace CommonData.Entity
{
    using System;
    using System.Reflection;

    public static class EntityFactory
    {
        public static T ConvertValue<T>(Type type, object value)
        {
            if (value == DBNull.Value)
            {
                return default(T);
            }
            return (T) Convert.ChangeType(value, type);
        }

        public static object ConvertValue(Type type, object value)
        {
            if (value == DBNull.Value)
            {
                return null;
            }
            return Convert.ChangeType(value, type);
        }

        public static T CreateInstance<T>() where T: class
        {
            Type type = typeof(T);
            object obj2 = Activator.CreateInstance<T>();
            return (T) obj2;
        }

        public static object CreateInstance(Type type, params object[] param)
        {
            return Activator.CreateInstance(type, param);
        }

        public static object CreateInstance(Type type, bool nonPublic)
        {
            return Activator.CreateInstance(type, nonPublic);
        }

        public static object GetPropertyValue(IEntity entity, string name)
        {
            PropertyInfo property = entity.GetType().GetProperty(name);
            object obj2 = null;
            if (property != null)
            {
                obj2 = property.GetValue(entity, null);
            }
            return obj2;
        }

        public static T GetPropertyValue<T>(IEntity entity, string name) where T: class
        {
            object propertyValue = GetPropertyValue(entity, name);
            if (propertyValue == null)
            {
                return default(T);
            }
            return (T) propertyValue;
        }

        public static object GetPropertyValue(object entity, string name)
        {
            PropertyInfo property = entity.GetType().GetProperty(name);
            object obj2 = null;
            if (property != null)
            {
                obj2 = property.GetValue(entity, null);
            }
            return obj2;
        }

        public static void SetPropertyValue(IEntity entity, string name, object value)
        {
            PropertyInfo property = entity.GetType().GetProperty(name);
            if (property != null)
            {
                property.SetValue(name, value, null);
            }
        }
    }
}

